//
//  NetworkSocket.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/4/14.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "NetworkSocket.h"
#import "UserModel.h"
#import "NSString+MD5.h"

#import <SVProgressHUD.h>
#import <GCDAsyncSocket.h>

#define SocketOfflineByUser @"SocketOfflineByUser" //用户主动cut
#define SocketOfflineByServer @"SocketOfflineByServer" //服务器掉线

@interface NetworkSocket()<GCDAsyncSocketDelegate>

@property (strong, nonatomic) GCDAsyncSocket *clinetSocket;
@property (strong, nonatomic) NSTimer *connectTimer;
@property (strong, nonatomic) UserModel *userModel;

@end

@implementation NetworkSocket

singleton_implementation(NetworkSocket)

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

-(GCDAsyncSocket *)clinetSocket{
    
    if (!_clinetSocket) {
        _clinetSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        _clinetSocket.delegate = self;
    }
    return _clinetSocket;
}

#pragma mark 连接socket
-(void)socketConnected{
    
    self.clinetSocket.userData = SocketOfflineByServer;
    
    NSURL *socketUrl = [NSURL URLWithString:NC_SOCKET_ITALY_URL];
    
    NSError *error = nil;
    
    [self.clinetSocket connectToHost:socketUrl.host onPort:NC_SOCKET_PORT withTimeout:-1 error:&error];
    
}

#pragma mark 切断socket
-(void)cutOffSocket{
    
    self.clinetSocket.userData = SocketOfflineByUser;
    
    [self.connectTimer invalidate];
    
    [self.clinetSocket disconnect];
}

#pragma mark 连接成功回调
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
    NSLog(@"host %@ port %hu",host,port);
    
#warning 密码
    
    NSString *newPassword = [NSString stringWithFormat:@"HYZ%@%@",self.userModel.userName,@"123456"];
    
    NSString *md5Password = [NSString stringToMD5:newPassword];
    
    NSString *loginString = [NSString stringWithFormat:@"10001{\"Pwd\":\"%@\",\"Id\":%@,\"User\":\"%@\",\"ClientType\":%@}",md5Password,self.userModel.userID,self.userModel.userName,self.userModel.clientType];
    
    NSLog(@"loginString %@",loginString);
    
    NSData *loginData = [loginString dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.clinetSocket writeData:loginData withTimeout:-1 tag:1];
    
#warning 时间
    //心跳
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:(10 * 60) repeats:YES block:^(NSTimer * _Nonnull timer) {
        
        NSString *longConnectString = [NSString stringWithFormat:@"10002%@",self.userModel.userID];
        
        NSLog(@"longConnectString %@",longConnectString);
        
        NSData *dataStream = [longConnectString dataUsingEncoding:NSUTF8StringEncoding];
        
        [self.clinetSocket writeData:dataStream withTimeout:-1 tag:1];
        
    }];
    
    [self.connectTimer fire];
    
}

#pragma mark 收到信息回调
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"Socket dataString %@",dataString);
    
    [SVProgressHUD showWithStatus:dataString];
    
    [self.clinetSocket readDataWithTimeout:-1 tag:tag];
    
}

#pragma mark 断开回调
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    
    NSLog(@"sorry the connect is failure %@",sock.userData);
    if ([sock.userData isEqualToString:SocketOfflineByServer]) {
        // 服务器掉线，重连
        NSLog(@"%@",SocketOfflineByServer);
        [self socketConnected];
    }
    else if ([sock.userData isEqualToString:SocketOfflineByUser]) {
        // 如果由用户断开，不进行重连
        NSLog(@"%@",SocketOfflineByUser);
        [self.connectTimer invalidate];
        return;
    }
    
}

@end
